import sys
import re

def count_characters(text):
    return len(text)

def count_words(text):
    words = re.findall(r"[A-Za-z]+", text)
    return len(words)

def count_sentences(text):
    sentences = re.findall(r"[\.!?]", text)
    return len(sentences)

# --------------------------------------
# 新增：统计代码行、空行、注释行
# --------------------------------------

def count_lines_info(text):
    lines = text.splitlines()

    total = len(lines)
    empty = 0
    comment = 0
    code = 0

    inside_block = False

    for line in lines:
        stripped = line.strip()

        # 空行统计
        if stripped == "":
            empty += 1
            continue

        # 块注释开始
        if stripped.startswith("/*"):
            comment += 1
            inside_block = True
            continue

        # 块注释中
        if inside_block:
            comment += 1
            if "*/" in stripped:
                inside_block = False
            continue

        # 单行注释
        if stripped.startswith("#") or stripped.startswith("//"):
            comment += 1
            continue

        # 剩下的视为代码行
        code += 1

    return total, empty, comment, code

# --------------------------------------

def main():
    # 参数检查
    if len(sys.argv) != 3:
        print("Usage: wc.exe [-c | -w | -s | -lc | -le | -lm | -la] <filename>")
        sys.exit(1)

    option = sys.argv[1]
    filename = sys.argv[2]

    # 读取文件
    try:
        with open(filename, "r", encoding="utf-8") as f:
            text = f.read()
    except FileNotFoundError:
        print(f"Error: cannot open file '{filename}'")
        sys.exit(1)

    # 原功能
    if option == "-c":
        print(count_characters(text))
    elif option == "-w":
        print(count_words(text))
    elif option == "-s":
        print(count_sentences(text))

    # 新功能：代码行统计
    elif option in ["-lc", "-le", "-lm", "-la"]:
        total, empty, comment, code = count_lines_info(text)

        if option == "-lc":
            print(code)
        elif option == "-le":
            print(empty)
        elif option == "-lm":
            print(comment)
        elif option == "-la":
            print(f"Total lines: {total}")
            print(f"Empty lines: {empty}")
            print(f"Comment lines: {comment}")
            print(f"Code lines: {code}")

    else:
        print("Invalid option. Use -c / -w / -s / -lc / -le / -lm / -la")
        sys.exit(1)

if __name__ == "__main__":
    main()
